package com.example.logisticsingle.Contorller;


import com.example.logisticsingle.String.StringUtils;
import com.example.logisticsingle.authorization.AuthProperties;
import com.example.logisticsingle.authorization.IAMUserDetailsService;
import com.example.logisticsingle.constants.ResponseEnum;
import com.example.logisticsingle.dto.Result;
import com.example.logisticsingle.dto.UsernamePassowrdLoginParams;
import com.example.logisticsingle.entity.SSOUser;
import com.example.logisticsingle.utils.ResultUtils;
import com.example.logisticsingle.utils.SSOLoginStoreHelper;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * sso server (for app)
 *
 */
@RestController
@Slf4j
@RequestMapping("/authentication")
public class AuthController {
    @Autowired
    private IAMUserDetailsService userDetailsService;

    @PostMapping("/form")
    @ApiOperation(value="用户通过用户名和密码登录",notes="用户通过用户名和密码登录，返回Token",httpMethod = "POST")
    public Result<?> loginByusernameAndPassword(@ModelAttribute @ApiParam(name="param",value="登录参数",required=true)
                                                UsernamePassowrdLoginParams param, HttpServletRequest request) {
        log.info("coming.....");
        return null;
    }

//	@RequestMapping("/hello")
//	public String hello() {
//		return "hello";
//	}
    /**
     * Token校验接口
     * @param request
     * @param token
     * @return
     */
    @ApiOperation(value = "获取用户登录信息", notes = "根据Token来获取用户详细信息")
    @ApiImplicitParam(name = "token", value = "登录Token(必填)", required = true, dataType = "String", paramType = "path")
    @GetMapping(value = "/validate/token/{token}",produces="application/json;charset=UTF-8")
    public Result<?> validateToken(HttpServletRequest request,@PathVariable String token){
        String tokenPrefix = AuthProperties.token.prefix;
        if(StringUtils.isNotNull(token) && token.startsWith(tokenPrefix)) {
            SSOUser user = SSOLoginStoreHelper.get(token);
            if(null!=user) {
                try {
                    UserDetails userDetails = this.userDetailsService.loadUserByUsername(user.getUsername());
                    //可以校验token和username是否有效，目前由于token对应username存在redis，都以默认都是有效的
                    UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
                            userDetails, null, userDetails.getAuthorities());
                    authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(
                            request));
                    SSOLoginStoreHelper.updateToken(token);
                    log.info("authenticated user " + user.getUsername() + ", setting security context");
                    SecurityContextHolder.getContext().setAuthentication(authentication);
                    Result<SSOUser> result= ResultUtils.sucess(ResponseEnum.SUCCESS);
                    result.setData(user);
                    return result;
                } catch (UsernameNotFoundException e) {
                    Result<?> result = ResultUtils.failure(ResponseEnum.LOGIN_TOKEN_FAIL);
                    return result;
                }
            }

        }
        Result<?> result = ResultUtils.failure(ResponseEnum.TOKEN_INVALID);
        return result;
    }
    @ApiOperation(value = "用户注销操作", notes = "用户退出")
    @DeleteMapping("/logout")
    public void logout(HttpServletRequest request){

    }

}
